<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/include/tag.jsp"%>
<%@ include file="/WEB-INF/include/common.jsp"%>
<style type="text/css">
td>label{
	width: 120px;
}

.huozhui{
	position: relative;
	left:-25px
}
input,select{
	font-size: 14px;
}
.col-sm-3 button{
	padding: 0;
}
</style>
<link rel="stylesheet" href="${ctx}/statics/css/custom_theme.css" />
<div class="modal fade" id="loanRateModel" tabindex="-1" role="dialog" aria-labelledby="userRoleModelLabel" aria-hidden="true" data-backdrop="false">
    <div class="modal-dialog">
        <div class="modal-content" style="width: 490px;">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                	<span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="userRoleModelLabel">贷款利率调整</h4>
            </div>
            <div class="modal-body">
        		<form id="loan_interest_form" class="form-horizontal" enctype="multipart/form-data">
        			 <input type="hidden" data="value" id="loan_interest_id" name="id">
					<table class="table table-condensed" id="table_interest">
						<c:forEach var="item" items="${itemList}" varStatus="status" >
							<tr>
								<td>
									<c:if test="${status.index ==0}">
										<label style="width: 70px">周期选择：</label>
									</c:if>
								</td>
								<td>
									<div class="checkbox" style="width: 70px">
										<input type="hidden" id="loan_interest_${item.itemName}" value="">
										<label> <input type="checkbox" id="box_${item.itemName}" value="${item.itemName}" name="installment" onchange="checkInterest(this,'${item.itemName }')">${item.itemName }期
										</label>
									</div>
								</td>
								<td><label style="width: 50px;padding-top: 7px;">利率：</label></td>
								<td>
									<input data="disabled" type="text" disabled="disabled" name="interest${item.itemName}" id="interest${item.itemName}" value="" number="true" min="0.0001"maxlength="4" max="0.99999" required style="width: 120px"/>
								</td>
							</tr>
		                </c:forEach>
					</table>
				</form>
            </div>
             <div class="modal-footer">
            	<button type="button" class="btn btn-sm btn-primary" id="rateModelBtn">确定</button>
                <button type="button" class="btn btn-sm btn-default" data-dismiss="modal" id="Close">关闭</button>
            </div>
        </div>
         
    </div>
</div>

<!-- 模态窗口 -->
<div class="modal fade" id="userModel" tabindex="-1" role="dialog" aria-labelledby="userModelLabel" aria-hidden="true" data-backdrop="false">
  <div class="modal-dialog" style="width:700px;">
        <div class="modal-content">
            <div class="modal-header">
            	<button type="button" class="close" data-dismiss="modal" aria-label="Close">
                	<span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" >添加贷款产品</h4>
            </div>
            <div class="modal-body">
            	<form id="loan_edit_form" class="form-horizontal" enctype="multipart/form-data">
			        <input type="hidden" id="loan_id" name="id">
			        <table class="table-condensed" >
			        	<tr>
			        		<td><label >产品名称</label></td>
			        		<td>
			        			<div class="group">
				        			<input type="text" id="productName" name="productName">
				        		</div>
			        		</td>
			        		<td><label >限定品牌名称</label></td>
			        		<td>
				        		<select id="limitedBrands" class="multiselect" multiple="multiple" name="limitedBrands" style="width:168px;">
					            	<c:forEach var="brand" items="${brandList}" varStatus="status" >
										<option value="${brand.name }">${brand.name }</option>
					                  </c:forEach>
								</select>
			        		</td>
			        	</tr>
			        	<tr>
			        		<td><label >产品类型</label></td>
			        		<td>
			        			<select id="loanType" name="loanType" style="width:168px;">
			        				<option value="1">银行</option>
				        			<option value="0">p2p</option>
				        		</select>
			        		</td>
			        		<td><label >是否需要抵押</label></td>
			        		<td>
				        		<select id="isPledge" name="isPledge" style="width:168px;">
									<option value="0">否</option>
									<option value="1">是</option>
								</select>
			        		</td>
			        	</tr>
			        	
			        	<tr>
			        		<td><label >最高贷款额度</label></td>
			        		<td>
			        			<div class="group">
				        			<input type="text" id="amount" name="amount" >
				        			<label class="huozhui">元</label>
				        		</div>
			        		</td>
			        		<td><label >首付比例</label></td>
			        		<td>
			        			<div class="group">
				        			<input  type="text" id="payment" name="payment">
				        			<label class="huozhui">%</label>
				        		</div>
			        		</td>
			        	</tr>
			        	<tr>
			        		
			        		<td><label >办理周期</label></td>
			        		<td>
			        			<div class="group">
					        		<input type="text" id="period" name="period">
				        			<label class="huozhui">天</label>
				        		</div>
			        		</td>
			        		<td><label >信誉要求</label></td>
			        		<td><input type="text" id="credit" name="credit"></td>
			        	</tr>
			        	<tr>
			        	</tr>
			        	<tr>
			        		<td><label >贷款最低资历</label></td>
			        		<td>
			        			<div class="group">
				        			<input type="text" id="minAptitude" name="minAptitude" >
				        			<label class="huozhui">岁</label>
				        		</div>
			        		</td>
			        		<td><label >贷款最高资历</label></td>
			        		<td>
			        			<div class="group">
					        		<input type="text" id="maxAptitude" name="maxAptitude">
				        			<label class="huozhui">岁</label>
				        		</div>
			        		</td>
			        	</tr>
			        	<tr>
			        		<td><label >收入最低要求</label></td>
			        		<td>
			        			<div class="group">
				        			<input type="text" id="income" name="income">
				        			<label class="huozhui">元</label>
				        		</div>
			        		</td>
			        		<td><label >办理场所</label></td>
			        		<td>
			        			<select id="place" name="place" style="width:168px;">
			        				<option value="0">线上/线下</option>
			        				<option value="1">线上</option>
			        				<option value="2">线下</option>
			        			</select>
			        		</td>
			        		
			        	</tr>
			        	<tr>
			        		<td><label >产品优先级</label></td>
			        		<td>
			        			<div class="group">
				        			<input type="text" id="proOrder" name="proOrder">
				        		</div>
			        		</td>
			        		<td><label >办理流程</label></td>
			        		<td><input type="text" id="process" name="process"></td>
			        	</tr>
			        	<tr>
			        		<td><label >法定代表人</label></td>
			        		<td><input type="text" id="representative" name="representative"></td>
			        		<td><label >提前还款方式</label></td>
			        		<td><input type="text" id="repayment" name="repayment"></td>
			        	</tr>
			        	<tr>
			        		<td><label >产品描述</label></td>
			        		<td><input type="text" id="described" name="described"></td>
			        		<td><label >企业名称</label></td>
			        		<td><input type="text" id="enterpriseName" name="enterpriseName"></td>
			        	</tr>
			        	<tr>
			        		<td><label >企业地址</label></td>
			        		<td><input type="text" id="enterpriseAddress" name="enterpriseAddress"></td>
			        	</tr>
			        	<tr>
			        		<td><label >上传logo</label></td>
			        		<td colspan="3"><input type="file" name="contractFile" class="file"/></td>
			        	</tr>
			        </table>
			    </form>
            </div>
            <div class="modal-footer">
            	<button type="button" class="btn btn-sm btn-primary" id="userModelBtn">确定</button>
                <button type="button" class="btn btn-sm btn-default" data-dismiss="modal" id="Close">关闭</button>
            </div>
        </div>
   </div>
</div>
<div id="main-content">
	<div class="row" >
		<div class="col-md-12">
			<div class="panel panel-default">
				<div class="panel-heading">${title}</div>
				<!-- /.panel-heading -->
				<div class="panel-body" >
					<div class="row">
						<div class="col-xs-12">
							<!-- PAGE CONTENT BEGINS -->
							<form class="form-horizontal" role="form" id="user_search_form">
								<div class="col-sm-9">
									<label class="col-sm-1 control-label">名称</label>
									<div class="col-sm-2">
										<input id="search_realName" name="productName" type="text"/> 
									</div>
								</div>
								<div class="col-sm-3">
									<button class="btn btn-sm btn-info" type="submit">
										<i class="icon-search nav-search-icon"></i>查询
									</button>
									<button type="button" class="btn btn-success btn-sm" onclick="addData()"><i class="icon-plus bigger-110"></i>新增</button>
									<button class="btn btn-sm btn-primary" type="reset"	>
										<i class="icon-undo bigger-110"></i>
										清除
									</button>
									<button type="button" class="btn btn-success btn-sm" onclick="exportLoan()"><i class="icon-plus bigger-110"></i>导出数据</button>
								</div>
							</form>
						</div>
					</div>
					<table id="user_table" class="table table-bordered">
					</table>
				</div>
			</div>
		</div>
	</div>
</div>
<script type="text/javascript">
$(function(){
	$('#limitedBrands').multipleSelect({
		placeholder:"选择品牌",
		selectAllText:"全选"
	});
	eachInstallment();
	$("#loan_interest_form").validate({
		submitHandler:function(form){
			$("#loanRateModel").prop("disabled",true);
			var id = $("#loan_interest_id").val();
			var arr = new Array();
			$("#loan_interest_form input:checked").each(function (index, domEle) { 
			 	var da = {
			 			"id":$("#loan_interest_"+$(this).val()).val(),
						"loanId":id,
						"installment":$(this).val(),
						"interest":$("#interest"+$(this).val()).val()
						}; 
			 	arr.push(da);
			});
			console.log(arr);
			 $.ajax({
					type:"post",
		   			url:"${ctx}/business/loan/saveOrUpdateInterest.do",
		   			data :{"json":JSON.stringify(arr),"loanId":id},
		   			success:function(data){
		   				if(data.success==true){
		   					$('#loanRateModel').modal('hide');
		   					$('#user_table').bootstrapTable('refresh');
		   				}else{
		   					alert(data.errorMessage);
		   				}
		             }  
		  	});
			$("#loanRateModel").prop("disabled",false);
        }  
	});
	
	//提交
	$("#loanRateModel").on('click','#rateModelBtn',function(){
		$("#loan_interest_form").submit();
	});
	
	$('#user_table').bootstrapTable({
		url: '${ctx}/business/loan/queryLoanList.do',
		pagination: true,
		paginationLoop: false,
		smartDisplay: false,
	    pageSize: 10,
	    pageList: [10, 20, 50, 100],
	    sidePagination: 'server',
	    paginationNextText:'下一页',
	    paginationPreText:'上一页',
	    cache: false,
	    detailView:true,
	    onExpandRow: function (index,row, $detail) {
	    	detailHtml(row,$detail);
		},
		columns: [
		 {
			field: '',
			title: '操作',
			align: 'center',
			width :'150px',
			formatter: function(value, row, index){
				return '<button class="btn btn-xs btn-success" id="editRate" title="利率调整"><i class=" icon-list-alt bigger-130"></i></button>'
						+'<button class="btn btn-xs btn-info" id="editData" title="编辑"><i class="icon-edit bigger-130"></i></button>'
						+'<button class="btn btn-xs btn-danger" id="deleteData" title="删除"><i class="icon-trash bigger-130"></i></button>';
			
			},
			events: {
				'click #editData': editData,
				'click #deleteData': deleteData,
				'click #editRate' :editRate
			}
		},{
			field: 'id',
			title: 'ID',
			align: 'center'
		},{
			field: 'productName',
			title: '产品名称',
			align: 'center'
		},{
			field: 'imageUrl',
			title: 'logo',
			align: 'center',
			formatter: function(value, row, index){
				if(row.imageUrl!=null && row.imageUrl!=""){
					return html='<img src="'+row.imageUrl+'" style="height:30px;"/>';
				}else{
					return "";
				}
			}
		},{
			field: 'amount',
			title: '最高贷款额度',
			align: 'center',
			formatter: function(value, row, index){
				return value==null?"-":value+"元";
			}
		},{
			field: 'payment',
			title: '首付比例',
			align: 'center',
			formatter: function(value, row, index){
				return value==null?"-":value+"%";
			}
		},{
			field: 'amountScale',
			title: '最高贷款比例',
			align: 'center',
			formatter: function(value, row, index){
				return value==null?"-":value+"%";
			}
		},{
			field: 'loanType',
			title: '产品类型',
			align: 'center',
			formatter: function(value, row, index){
				if(row.loanType==0){
					return "p2p";
				}else if(row.loanType==1){
					return "银行";
				}
			}
		},{
			field: 'isPledge',
			title: '是否需要抵押',
			align: 'center',
			formatter: function(value, row, index){
				if(row.isPledge==0){
					return "否";
				}else if(row.isPledge==1){
					return "是";
				}
			}
		},{
			field: 'limitedBrands',
			title: '限定品牌',
			align: 'center',
			formatter: function(value, row, index){
				return value==null?"-":value;
			}
		},{
			field: 'period',
			title: '办理周期',
			align: 'center',
			formatter: function(value, row, index){
				return value==null?"-":value+"工作日";
			}
		}],
		queryParams: function(params){
			//console.log(params);
			//params.usreId
			$.extend(params,$("#user_search_form").serializeJson());
			return params;
		}
	});

	$('#user_table').on('mouseenter','.pannel_a_title',function () {
        $(this).popover('show');
	});
	// 
	$.validator.addMethod("compare",function(value,element,param){  
		var target = $( param );
		return this.optional( element )|| value > target.val();
	},"不能小于最低资历");
	$.extend($.validator.messages, {
		digits: "只能输入整数"
	});
	//添加和编辑请求验证
	$("#loan_edit_form").validate({
		 errorPlacement: function(error, element) {
				// Append error within linked label
			 error.appendTo(element.parent("div").after("<label></label>").next("label"));
			},
		 rules: {
			 	productName: {required : true},
			    limitedBrands: {},
			    proOrder: {number:true,min : 0},
			    payment: {number:true,min : 0,max:100},
			    amount: {number:true,min : 0},
			    amountScale: {number:true,min : 0,max:100},
			    minAptitude: {digits:true,min : 0,max:100},
			    maxAptitude: {digits:true,min : 0,max:100,compare:"#minAptitude"},
			    income: {number:true,min : 0},
			    credit: {},
			    place: {},
			    process: {},
			    period: {digits:true,min : 0},
			    repayment: {},
			    installment: {},
			    described: {},
			    enterpriseName: {},
			    enterpriseAddress: {},
			    representative: {},
		},
		submitHandler: function(form) {
			$("#userModel").prop("disabled",true);
    		$(form).ajaxSubmit({
    			type:"post",
    			dataType:"json",
    			url:"${ctx}/business/loan/saveOrUpdate.do",
    			success:function(data){
    				if(data.success==true){
    					$('#userModel').modal('hide') 
    					$('#user_table').bootstrapTable('refresh');
    				}else{
    					alert(data.errorMessage);
    				}
    				$("#userModel").prop("disabled",false);
                }  
            });
		}
	});
	
	//提交用户信息
	$("#userModel").on('click','#userModelBtn',function(){
		$("#loan_edit_form").submit();
	});
	
	//搜索角色
	$("#user_search_form").submit(function(e){
		e.preventDefault();
		$('#user_table').bootstrapTable('refresh');
	});
	
});

//查询字典值列表
function queryDictItem(e, v, row){
	window.location.href="toDictItemPage.do?title=字典值管理&dictCode="+row.dictCode;
	//window.open("${ctx}/admin/dict/toDictItemPage.do?dictCode="+row.dictCode);
}

//添加
function addData(e, v, row) {
	$("#userModel .modal-title").empty().html("添加贷款产品");
	$("#loan_edit_form").validate().resetForm();
	$('#limitedBrands').multipleSelect('setSelects', []);
	$('#limitedBrands').prop("checked",false);
	$("#loan_edit_form input[name=id]").val("");
	//$("#loan_edit_form input[name=dictCode]").removeAttr("disabled");解除输入框禁用
	$('#userModel').modal('show');
}
function exportLoan(e, v, row) {
	window.location.href="${ctx}/business/loan/exportLoan.do"
}
//编辑
function editData(e, v, row) {
	$("#userModel .modal-title").empty().html("修改贷款产品");
	$("#loan_edit_form").validate().resetForm();
	$("#loan_edit_form input[name=id]").val(row.id);
	//$("#loan_edit_form input[name=dictName]").val(row.dictName);
	//$("#loan_edit_form input[name=dictCode]").val(row.dictCode);
	//$("#loan_edit_form input[name=dictCode]").attr("disabled","disabled");禁用输入框
	//$("#loan_edit_form input[name=dictRemark]").val(row.dictRemark);
	//$("#loan_edit_form input[name=isDisable]").val([row.isDisable]);
	$.ajax({
	        url: "${ctx}/business/loan/queryLoanById.do",
	        type: "POST",
	        data: {
	            "id": row.id
	        },
	        success: function (data) {
	        	if(data.success){
	        		//给输入框赋值
	        		$("#loan_edit_form input[name=productName]").val(data.result.productName);
	        		var limitedBrands = data.result.limitedBrands;
	        		var brands = limitedBrands.split(",");
	        		$('#limitedBrands').multipleSelect('setSelects', brands);
	        		$("#loan_edit_form input[name=limitedBrands]").val(data.result.limitedBrands);
	        		$("#loan_edit_form input[name=proOrder]").val(data.result.proOrder);
	        		$("#loan_edit_form input[name=payment]").val(data.result.payment);
	        		$("#loan_edit_form input[name=amount]").val(data.result.amount);
	        		$("#loan_edit_form input[name=amountScale]").val(data.result.amountScale);
	        		$("#loan_edit_form input[name=interest]").val(data.result.interest);
	        		$("#loan_edit_form input[name=credit]").val(data.result.credit);
	        		$("#loan_edit_form input[name=minAptitude]").val(data.result.minAptitude);
	        		$("#loan_edit_form input[name=maxAptitude]").val(data.result.maxAptitude);
	        		$("#loan_edit_form input[name=income]").val(data.result.income);
	        		$("#loan_edit_form select[name=place]").val(data.result.place);
	        		$("#loan_edit_form select[name=loanType]").val(data.result.loanType);
	        		$("#loan_edit_form select[name=isPledge]").val(data.result.isPledge);
	        		$("#loan_edit_form input[name=process]").val(data.result.process);
	        		$("#loan_edit_form input[name=period]").val(data.result.period);
	        		$("#loan_edit_form input[name=repayment]").val(data.result.repayment);
	        		$("#loan_edit_form input[name=installment]").val(data.result.installment);
	        		$("#loan_edit_form input[name=described]").val(data.result.described);
	        		$("#loan_edit_form input[name=enterpriseName]").val(data.result.enterpriseName);
	        		$("#loan_edit_form input[name=enterpriseAddress]").val(data.result.enterpriseAddress);
	        		$("#loan_edit_form input[name=representative]").val(data.result.representative);
	            }else {
	            	alert(data.errorMessage);
	            }
	        }
  		});
	$('#userModel').modal('show');
}

//删除用户
function deleteData(e, v, row) {
	if(confirm("确定删除吗？")){
		$.ajax({
	        url: "${ctx}/business/loan/deleteLoan.do",
	        type: "POST",
	        data: {
	            "id": row.id
	        }, 
	        success: function (data) {
	        	if(data.success){
	        		$('#user_table').bootstrapTable('refresh');
	            }else {
	            	alert(data.errorMessage);
	            }
	        }
  		});
	}
	
}
function editRate(e,v,row){
	$("#loan_interest_form").validate().resetForm();
	$("#loan_interest_form input[data=value]").val("");
	$("#loan_interest_form input[type=checkbox]").each(function (index, domEle) { 
	 	$(this).prop("checked",false);
	});
	$("#loan_interest_form input[data=disabled]").each(function (index, domEle) { 
	 	$(this).prop("disabled","disabled");
	});
	$("#loan_interest_id").val(row.id);
	//贷款利率调整
	 $.ajax({
	        url: "${ctx}/business/loan/getInterest.do",
	        type: "POST",
	        data: {
	            "id": row.id
	        }, 
	        success: function (data) {
        		var list = data.rows;
        		if(list.length>0){
	        		for(var i=0;i<list.length;i++){
	        			var id = list[i].id;
	        			var name = list[i].installment;
	        			var value = list[i].interest;
	        			$("#box_"+name).prop("checked",true);
	        			$("#interest"+name).removeAttr("disabled");
	        			$("#interest"+name).val(value);
	        			$("#loan_interest_"+name).val(id);
	        		}
        		}
        		$('#loanRateModel').modal('show');
	        }
  		}); 
	
	
}
function detailHtml(row,$detaile){
	console.log(row);
	var list = row.interestList;
	var html ='';
	html+='<table class="table"><tr><td>贷款周期</td>';
		if(list!=null&& list.length>0){
			for(var i=0;i<list.length;i++){
				html+='<td>'+list[i].installment+'期</td>';
			}
		}
		html+='</tr><tr><td>贷款利率</td>';
		if(list!=null&& list.length>0){
			for(var i=0;i<list.length;i++){
				html+='<td>'+list[i].interest+'</td>';
			}
		}
		html+='</tr></table>';
		if(row.minAptitude!=null && row.maxAptitude!=null){
			html+='<p><span style="font-size:14px"><strong>资质要求：</strong></span></p>';
			html+='<p><span style="font-size:14px">- 年龄：'+row.minAptitude+'-'+row.maxAptitude+'岁</span></p>';
		}
		if(row.payment!=null){
			html+= '<p><span style="font-size:14px">- 首付：(车辆开票价+购置税融资金额+保险融资金额)*'+row.payment+'%起</span></p>';
		}
		if(row.income!=null){
			html+= '<p><span style="font-size:14px">- 收入证明 ：'+row.income+'以上 </span></p>';
			
		}
		if(row.credit!=null){
			html+= '<p><span style="font-size:14px"><strong>信誉要求：</strong>'+row.credit+'</span></p>';
		}
		if(row.place!=null){
			var place =row.place;
			if(place==0){
				place="线上/线下";
			}else if(place==1){
				place="线上";
			}else{
				place="线下";
			}
			html+= '<p><span style="font-size:14px"><strong>办理场所：</strong>'+place+'</span></p>';
		}
		if(row.process!=null){
			html+= '<p><span style="font-size:14px"><strong>办理流程：</strong>'+row.process+'</span></p>';
		}
		if(row.described!=null){
			html+= '<p><span style="font-size:14px"><strong>产品优势：</strong>'+row.described+'</span></p>';
		}
			html+= '<p><span style="font-size:14px"><strong>月供计算方式：</strong>等额本息=（月还款额=本金*月利率*(1+月利率)^还款月数/[(1+月利率)^还款月数-1]）；</span></p>';
		if(row.repayment!=null){
			html+= '<p><span style="font-size:14px"><strong>提前还款方式：</strong>'+row.repayment+'</span></p>';
		}
		if(row.enterpriseName!=null){
			html+= '<p>企业名称：'+row.enterpriseName+'<br>住所地址：'+row.enterpriseAddress+'<br>法定代表人：'+row.representative+'</p>';
		}
	$detaile.html(html);
}

function checkInterest(data,id){
	$("#loan_interest_form").validate();
	if($(data).is(":checked")){
		$("#interest"+id).removeAttr("disabled");
	}else{
		$("#interest"+id).attr("disabled","disabled");
		$("#interest"+id).val("");
		
	}
}
function eachInstallment(){
	$("input[name=installment]").each(function (index, domEle) { 
		 var id =$(this).attr("id");
		 if($("#interest"+id).is(":checked")){
			 $("#interest"+id).removeAttr("disabled");
		}
	});
}

</script>